package com.hxzy.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.dto.ContamerLoginDTO;
import com.hxzy.dto.ContamerSearch;
import com.hxzy.entity.Contamer;
import com.hxzy.mapper.ContamerMapper;
import com.hxzy.service.ContamerService;
import com.hxzy.vo.ContamerLoginVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.List;

/**
 * 前端用户业务逻辑
 *
 * @author tonneyyy
 */
@Log4j2
@Service
public class ContamerServiceImpl extends ServiceImpl<Contamer,Integer>  implements ContamerService {

    private ContamerMapper  contamerMapper;

    @Autowired
    public void setContamerMapper(ContamerMapper contamerMapper) {
        this.contamerMapper = contamerMapper;
        super.setMyBatisBaseDao(contamerMapper);
    }

    @Override
    public List<Contamer> search(ContamerSearch contamerSearch) {
        return this.contamerMapper.search(contamerSearch);
    }

    @Override
    public ContamerLoginVO login(@Valid ContamerLoginDTO contamerLoginDTO) {
        Contamer dbContamer=this.contamerMapper.findByUserName(contamerLoginDTO.getLoginName());
        if(dbContamer==null){
            log.info(contamerLoginDTO.getLoginName()+","+ AckCode.USER_NOT_FOUND.getMsg());
            throw new ServiceException(AckCode.USERNAME_PASSWORD_ERROR);
        }

        //判断密码
        boolean checkpw = BCrypt.checkpw(contamerLoginDTO.getPassword(), dbContamer.getPasswold());
        if(!checkpw){
            log.info(contamerLoginDTO.getLoginName()+","+AckCode.LOGIN_PASSWORD_ERROR.getMsg());
            throw new ServiceException(AckCode.USERNAME_PASSWORD_ERROR);
        }

        //状态
        if(dbContamer.getStatus()==1){
            log.info(contamerLoginDTO.getLoginName()+","+AckCode.DEVICE_BANNED.getMsg());
            throw new ServiceException(AckCode.DEVICE_BANNED);
        }

        ContamerLoginVO  contamerLoginVO=new ContamerLoginVO();
        BeanUtils.copyProperties(dbContamer,contamerLoginVO);
        return contamerLoginVO;
    }


}
